home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 704 < prev    next >
Internet Message Format  |  1996-08-06  |  2KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.std.c
  4. Subject: Re: Is it legal to add 0 to NULL? What about NULL < NULL?
  5. Date: Sun, 07 Apr 96 19:34:53 GMT
  6. Organization: none
  7. Message-ID: <828905693snz@genesis.demon.co.uk>
  8. References: <ff1d.smail.smayo@tiac.net>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <ff1d.smail.smayo@tiac.net> smayo@tiac.net "Scott Mayo" writes:
  15.  
  16. >I ask because a standard trick for walking an array A of size S is:
  17. >
  18. >Thing *a = A;
  19. >Thing *fence = a + S;
  20. >for (; a < fence; ++a)
  21. >    /* use a */;
  22. >
  23. >but in my case, if S happens to be 0, a will start out NULL. This makes we
  24. >worry about both the value of fence, and, if that works, the behaviour
  25. >of (a < fence), which I hope is (NULL < NULL), which I hope the standard
  26. >blesses as reliably false, but I have this feeling that it won't.
  27.  
  28. The standard says about addition 6.3.6:
  29.  
  30. "If both the pointer and the result point to elements of the same array
  31.  object, or one past the last element of the array object, the evaluation
  32.  shall not produce an overflow; otherwise the behaviour is undefined"
  33.  
  34. Unfortunately a null pointer doesn't point to an array object so we
  35. invoke 'otherwise'.
  36.  
  37. Similarly comparison against a null pointer (even another one) is defined
  38. for equality operators == and != but not for relational operators < <= > >=.
  39.  
  40. If S can't be negative you could use:
  41.  
  42. >for (; a != fence; ++a)
  43.  
  44. But if you've already tested for S being zero, it probably doesn't help.
  45. As far as efficiency is concerned you could write:
  46.  
  47.     if (S > 0) {
  48.         Thing *a = A;
  49.         Thing *fence = a + S;
  50.  
  51.         do {
  52.             ...
  53.         } while (++a < fence);
  54.     }
  55.  
  56. >I know I can use int i; for (i = 0; i < S; ++i) but I was
  57. >hoping to avoid the extra math at array dereference time.
  58.  
  59. Any reasonable conpiler should be able to optimise that to a pointer as
  60. appropriate. It might even do a better job at optimising that than with the
  61. code above.
  62.  
  63. -- 
  64. -----------------------------------------
  65. Lawrence Kirby | fred@genesis.demon.co.uk
  66. Wilts, England | 70734.126@compuserve.com
  67. -----------------------------------------
  68.